<template>
  <div class="material-list-container">
    <!-- 添加操作区域 -->
    <div class="operation-area">
      <div class="left-buttons">
        <el-button type="primary" @click="handleAddMaterial">添加课件</el-button>
        <el-button :disabled="!selectedRows.length" type="danger" @click="handleBatchRemove">
          批量移除<span v-if="selectedRows.length">({{ selectedRows.length }})</span>
        </el-button>
      </div>
    </div>

    <!-- 表格区域 -->
    <el-table
      :data="selectedMaterials"
      border
      style="width: 100%"
      @selection-change="handleSelectionChange"
      row-key="id"
    >
      <!-- 替换拖拽列为多选框列 -->
      <el-table-column type="selection" width="40" />
      <el-table-column
        label="文件名称"
        max-width="250"
        min-width="150"
        prop="name"
        show-overflow-tooltip
        align="left"
        class="filename-column"
      />
      <el-table-column align="center" label="文件类型" prop="type" width="120">
        <template #default="{ row }">
          {{ formatFileType(row.fileType) }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="完成时长" prop="duration" width="220">
        <template #default="{ row }">
          <div style="cursor: pointer" @dblclick="handleStartEdit(row, 'duration')">
            <template v-if="editingCell.id === row.id && editingCell.field === 'duration'">
              <div class="editing-cell">
                <el-time-picker
                  v-model="editingCell.timeValue"
                  :placeholder="'请选择时长'"
                  format="HH:mm:ss"
                  value-format="HH:mm:ss"
                  @blur="handleBlur"
                  @change="handleTimeChange"
                />
              </div>
            </template>
            <template v-else>
              {{ formatDuration(row.duration) }}
            </template>
          </div>
        </template>
      </el-table-column>
      <el-table-column align="center" label="完成积分" prop="points" width="200">
        <template #default="{ row }">
          <div class="editable-cell" @click="handleStartEdit(row, 'points')">
            <template v-if="editingCell.id === row.id && editingCell.field === 'points'">
              <div class="editing-cell">
                <el-input-number
                  v-model="editingCell.value"
                  :min="0"
                  @blur="handleBlur"
                  @change="handleChange"
                />
              </div>
            </template>
            <template v-else>
              {{ row.points }}
            </template>
          </div>
        </template>
      </el-table-column>
      <!-- 添加操作列 -->
      <el-table-column label="操作" width="100" fixed="right">
        <template #default="{ row }">
          <el-button type="danger" link @click="handleRemove(row.id)"> 移除 </el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script setup lang="ts">
import { useCentreStore } from '@/store/modules/lession/centre'
import { storeToRefs } from 'pinia'
import { nextTick, onBeforeUnmount, onMounted, ref } from 'vue'
import Sortable from 'sortablejs'
import { ElMessage, ElMessageBox } from 'element-plus'

interface Material {
  id: number
  name: string
  type: string
  catalog: string
  size: number
  duration: number
  createTime: string
}

// Emits 定义
const emit = defineEmits(['selection-change', 'add-material'])

// 添加 store 的初始化
const centreStore = useCentreStore()

// 使用 storeToRefs 来保持响应性
const { selectedMaterials } = storeToRefs(centreStore)

// 添加选中行的状态
const selectedRows = ref<Material[]>([])

// 修改格式化文件类型的函数
const formatFileType = (type: string) => {
  const typeMap: Record<string, string> = {
    '1': '视频',
    '2': '文档',
    '3': '音频',
    '4': '图片',
    '5': '压缩包'
  }
  console.log('type', type)
  return typeMap[type] || '未知类型'
}

// 修改选择变化处理函数
const handleSelectionChange = (selection: Material[]) => {
  selectedRows.value = selection
  emit('selection-change', selection)
}

// 添加移除方法
const handleRemove = (materialId: number) => {
  centreStore.removeMaterial(materialId)
}

// 添加课件处理方法
const handleAddMaterial = () => {
  emit('add-material')
}

// 修改批量移除方法
const handleBatchRemove = () => {
  if (!selectedRows.value.length) {
    ElMessage.warning('请先选择要移除的课件')
    return
  }

  ElMessageBox.confirm(`确定要移除选中的 ${selectedRows.value.length} 个课件吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      selectedRows.value.forEach((material) => {
        centreStore.removeMaterial(material.id)
      })
      selectedRows.value = [] // 清空选中状态
      ElMessage.success('批量移除成功')
    })
    .catch(() => {})
}

// 修改拖拽功能配置
onMounted(() => {
  const tbody = document.querySelector('.el-table__body-wrapper tbody')
  if (tbody) {
    new Sortable(tbody, {
      animation: 150,
      handle: '.el-table__row',
      ghostClass: 'sortable-ghost',
      dragClass: 'sortable-drag',
      filter: '.el-checkbox', // 防止点击checkbox时触发拖拽
      onEnd({ newIndex, oldIndex }) {
        if (newIndex === undefined || oldIndex === undefined) return
        const currRow = selectedMaterials.value.splice(oldIndex, 1)[0]
        selectedMaterials.value.splice(newIndex, 0, currRow)
        centreStore.setSelectedMaterials([...selectedMaterials.value])
      }
    })
  }

  // 添加点击事件监听
  document.addEventListener('mousedown', handleClickOutside)
})

// 在组件卸载前移除事件监听
onBeforeUnmount(() => {
  document.removeEventListener('mousedown', handleClickOutside)
})

// 修改点击外部处理函数
const handleClickOutside = (event: MouseEvent) => {
  // 如果当前没有在编辑状态，直接返回
  if (!editingCell.value.id) return

  // 获取当前编辑的元素
  const editingElement = document.querySelector('.editing-cell')
  if (!editingElement) return

  // 检查是否点击在时间选择器弹出框内
  const timePickerDropdown = document.querySelector('.el-time-picker__panel')
  if (timePickerDropdown?.contains(event.target as Node)) {
    return
  }

  // 检查点击是否在编辑元素外部
  if (!editingElement.contains(event.target as Node)) {
    // 如果是时间选择器，需要保存当前值
    if (editingCell.value.field === 'duration' && editingCell.value.timeValue) {
      handleTimeChange(editingCell.value.timeValue)
    }

    // 重置编辑状态
    editingCell.value = {
      id: null,
      field: '',
      value: null,
      timeValue: ''
    }
  }
}

// 添加自定义指令用于自动聚焦
const vFocus = {
  mounted: (el: HTMLElement) => {
    nextTick(() => {
      // 找到input元素并聚焦
      const input = el.querySelector('input')
      input?.focus()
    })
  }
}

// 修改编辑状态管理
const editingCell = ref({
  id: null as number | null,
  field: '',
  value: null as number | null,
  timeValue: '' as string // 改为字符串类型
})

// 将秒数转换为时间字符串
const secondsToTimeString = (seconds: number) => {
  if (!seconds) return '00:00:00'
  const hours = Math.floor(seconds / 3600)
  const minutes = Math.floor((seconds % 3600) / 60)
  const remainingSeconds = seconds % 60
  return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`
}

// 将时间字符串转换为秒数
const timeToSeconds = (timeStr: string) => {
  if (!timeStr) return 0
  const [hours, minutes, seconds] = timeStr.split(':').map(Number)
  return (hours || 0) * 3600 + (minutes || 0) * 60 + (seconds || 0)
}

// 修改开始编辑方法
const handleStartEdit = (row: any, field: string) => {
  if (field === 'duration') {
    editingCell.value = {
      id: row.id,
      field,
      value: null,
      timeValue: secondsToTimeString(row.duration || 0)
    }
  } else {
    editingCell.value = {
      id: row.id,
      field,
      value: row[field],
      timeValue: ''
    }
  }
}

// 修改 handleTimeChange 方法
const handleTimeChange = (value: string) => {
  if (editingCell.value.id === null || !editingCell.value.field) return

  // 如果值为空，不进行更新
  if (!value) return

  const seconds = timeToSeconds(value)
  const index = selectedMaterials.value.findIndex((item) => item.id === editingCell.value.id)

  if (index !== -1) {
    const updatedMaterial = {
      ...selectedMaterials.value[index],
      duration: seconds
    }
    // 直接更新到 store
    centreStore.updateMaterial(updatedMaterial)
  }
}

// 格式化显示时长（与 secondsToTimeString 相同）
const formatDuration = (duration: number) => {
  if (!duration) return '00:00:00'
  const hours = Math.floor(duration / 3600)
  const minutes = Math.floor((duration % 3600) / 60)
  const seconds = duration % 60
  return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`
}

// 修改handleChange方法
const handleChange = (value: number) => {
  if (editingCell.value.id === null || !editingCell.value.field) return

  const index = selectedMaterials.value.findIndex((item) => item.id === editingCell.value.id)
  if (index !== -1) {
    const updatedMaterial = {
      ...selectedMaterials.value[index],
      [editingCell.value.field]: value
    }
    // 更新 store 中的数据
    centreStore.updateMaterial(updatedMaterial)
  }
}

// 修改 handleBlur 方法
const handleBlur = () => {
  // 不在这里重置编辑状态，让 handleClickOutside 来处理
}
</script>

<style scoped>
.material-list-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

/* 操作区域样式 */
.operation-area {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  background-color: var(--el-bg-color);
  border-radius: 4px;
  border: 1px solid var(--el-border-color-lighter);
}

.left-buttons {
  display: flex;
  gap: 12px;
}

.search-area {
  padding: 16px;
  background-color: var(--el-bg-color);
  border-radius: 4px;
}

.pagination-container {
  padding: 16px;
  display: flex;
  justify-content: flex-end;
  background-color: var(--el-bg-color);
  border-radius: 4px;
}

:deep(.el-table) {
  flex: 1;
  --el-table-border-color: var(--el-border-color-lighter);
  --el-table-header-bg-color: var(--el-fill-color-light);
}

:deep(.el-form--inline .el-form-item) {
  margin-right: 16px;
  margin-bottom: 0;
}

:deep(.el-input) {
  width: 200px;
}

:deep(.el-select) {
  width: 200px;
}

/* 移除不需要的样式 */
:deep(.el-table__row) {
  cursor: move;
  transition: all 0.3s;
}

:deep(.el-table__row:hover) {
  background-color: var(--el-table-row-hover-bg-color);
}

:deep(.sortable-ghost) {
  opacity: 0.6;
  background: var(--el-color-primary-light-9) !important;
}

:deep(.sortable-drag) {
  background: var(--el-bg-color) !important;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

/* 确保复选框可以正常点击 */
:deep(.el-checkbox) {
  cursor: pointer;
}

/* 添加选中数量的样式 */
.el-button span {
  margin-left: 4px;
  font-size: 12px;
}

:deep(.el-input-number) {
  width: 100%;
}

:deep(.el-input-number .el-input__wrapper) {
  padding: 0 8px;
}

:deep(.el-time-picker) {
  width: 100%;
  height: 23px; /* 设置固定高度 */
}

:deep(.el-time-picker .el-input__wrapper) {
  padding: 0 8px;
  height: 23px; /* 设置固定高度 */
  line-height: 23px;
}

:deep(.el-time-picker .el-input__inner) {
  height: 23px;
  line-height: 23px;
  font-size: 12px; /* 调整字体大小 */
}

:deep(.el-time-picker .el-input) {
  height: 23px;
  line-height: 23px;
}

/* 调整表格单元格高度 */
:deep(.el-table__cell) {
  height: 23px;
  line-height: 23px;
  padding: 4px 0;
}

/* 确保编辑状态下的内容垂直居中 */

/* 为需要居中的列单独添加样式 */
:deep(.el-table__cell.is-center .cell) {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
}

/* 添加编辑单元格的样式 */
:deep(.editing-cell) {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 添加可编辑单元格的样式 */
.editable-cell {
  width: 100%;
  height: 100%;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
}

.editable-cell:hover {
  background-color: var(--el-fill-color-light);
}
</style>
